package com.beautiful.xin.sort;


import java.util.Arrays;

/**
 * @author xuqingxin 2021/8/9 10:06 下午
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {2, 6, 7, 1, 9, 4, 5, 3};
        mergesort(arr, 0, arr.length - 1, new int[arr.length]);
        for (int i = 0; i < arr.length; i++) {

            System.out.print(arr[i] + " ");
        }
    }

    public static void mergesort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergesort(arr, left, mid, temp);
            mergesort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            temp[t++] = arr[i] >= arr[j] ? arr[j++] : arr[i++];
        }
        while (i <= mid) {
            temp[t++] = arr[i++];
        }
        while (j <= right) {
            temp[t++] = arr[j++];
        }
        t = 0;
        int tleft = left;
        while (tleft <= right) {
            arr[tleft++] = temp[t++];
        }
    }



}
